package com.touch.app.common.util;

import com.alibaba.fastjson.JSON;
import com.touch.app.common.domain.Ask;
import com.touch.app.common.domain.ChatGPTMessage;
import com.touch.app.common.domain.ChatGPTRequest;
import lombok.Data;

import java.util.*;

@Data
public class ChatGPT {
    private String token;
    private String url;
    private Ask ask;
    private Date askTime;
    private Map<String, String> headers;

    public ChatGPT(String url) {
        this.url = url;
    }

    public ChatGPT(String token, String url) {
        this.token = token;
        this.url = url;
    }

    private ChatGPTRequest setRequest(String question) {
        ChatGPTMessage message = new ChatGPTMessage(question);
        List<ChatGPTMessage> messageList = new LinkedList<>();
        messageList.add(message);
        return new ChatGPTRequest(messageList);
    }

    private void headers() {
        if (headers == null || headers.isEmpty()) {
            this.headers = new HashMap<>();
            headers.put("Content-Type","application/json");
            headers.put("Authorization", "Bearer " + token);
        }
    }

    public String ask(Ask ask) {
        this.ask = ask;
        this.askTime = new Date();
        headers();
        String request = JSON.toJSONString(setRequest(ask.getQuestion()));
        return HttpUtils.post(url, headers, request);
    }

    public String ask(ChatGPTRequest gptRequest) {
        this.askTime = new Date();
        headers();
        String request = JSON.toJSONString(gptRequest);
        return HttpUtils.post(url, headers, request);
    }
}
